<?php

namespace app\controller\admin;

use app\BaseController;
use think\facade\Cache;
use think\facade\Db;

class AdminController extends BaseController
{

    public function search()
    {
        $company_name = input("company_name");
        if (!$company_name) {
            return retError('请输入公司名称');
        }

        $url = "http://192.168.10.190:8211/upload_company_name/";

        // 初始化cURL会话
        $ch = curl_init($url);

        // 设置cURL选项
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // 返回结果不直接输出
        curl_setopt($ch, CURLOPT_POST, true); // 设置为POST请求
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode(['upload_company_name' => $company_name])); // POST请求的数据，以JSON格式发送
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            "Content-Type: application/json; charset=utf-8",
        ));
        // 执行cURL会话
        $response = curl_exec($ch);

        // 检查是否有错误发生
        if (curl_errno($ch)) {
            return retError('操作失败');
        }

        // 关闭cURL资源
        curl_close($ch);
        $result = json_decode($response, true);

        if ($result['code'] == 200) {
            $addData['company_name'] = $company_name;
            $addData['uid'] = $result['uid'];
            $addData['status'] = 0;
            $addData['create_time'] = time();
            $addData['file_path'] = '';
            $addData['file_url'] = '';

            $id = Db::name("log")->insertGetId($addData);

            return retJson($id);
        } else {
            return retError('操作失败');
        }
    }

    public function addLog()
    {
        $log_id = input("log_id");
        $path = input("path");


        $data['log_id'] = $log_id;
        $data['file_path'] = $path;

        $unknown = 'unknown';

        if (isset($_SERVER['HTTP_X_FORWARDED_FOR']) && $_SERVER['HTTP_X_FORWARDED_FOR'] && strcasecmp($_SERVER['HTTP_X_FORWARDED_FOR'], $unknown)) {
            $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
        } elseif (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], $unknown)) {
            $ip = $_SERVER['REMOTE_ADDR'];
        } else {
            $ip = $unknown;
        }
        $data['ip'] = $ip;
        Db::name("download_log")->insert($data);

        return retJson();
    }


    public function showLog()
    {
        $rst = Db::name("download_log")->alias('a')->leftJoin("log b", 'a.log_id = b.id')->select();

        // 开始输出表格
        echo '<table border="1">';
        echo '<tr><th>ID</th><th>UID</th><th>公司名称</th><th>Path</th><th>IP</th></tr>'; // 表头

        foreach ($rst as $row) {
            echo '<tr>'; // 开始新的一行
            echo '<td>' . $row['log_id'] . '</td>'; // 单元格
            echo '<td>' . $row['uid'] . '</td>'; // 单元格
            echo '<td>' . $row['company_name'] . '</td>'; // 单元格

            echo '<td>' . $row['file_path'] . '</td>'; // 单元格
            echo '<td>' . $row['ip'] . '</td>'; // 单元格
            echo '</tr>'; // 结束这一行
        }

        echo '</table>'; // 结束表格
    }


    public function getTaskTstatus($uid = "")
    {
        $response = file_get_contents("http://192.168.10.190:8211/task_status/" . $uid);
        $response = json_decode($response, true);
        return $response;
    }

    public function cancelTask($uid = "")
    {
        $response = file_get_contents("http://192.168.10.190:8211/cancel_task/" . $uid);
        $response = json_decode($response, true);
        if ($response['code'] == 200) {
            Db::name("log")->where("uid", $uid)->update(['status' => 3]);
        }
        return retJson($response);
    }

    public function getList()
    {
        $ids = input("ids");
        $page = input("page");
        if (!$page) {
            $page = 1;
        }
        $ids = explode(",", $ids);

        $new = [];
        foreach ($ids as $row) {
            if ($row) {
                $new[] = $row;
            }
        }
        $ids = join(",", $new);

        $size = 8;

        $where = '';
        if ($ids) {
            $where = "id in ($ids)";
        }

        $result = Db::name("log")->where($where)->whereOr("id <=51")->order("id desc")->paginate(['list_rows' => $size ?: 10, 'page' => $page ?: 1])
            ->each(function ($item) {
                if ($item['status'] == 0) {
                    $item['status'] = $this->check($item['uid']);
                }
                $create_timestamp = $item['create_time'];
                $item['create_time'] = date("Y-m-d H:i:s", $item['create_time']);
                if ($item['status'] == 0) {
                    if ((time() - $create_timestamp) > (60 * 20)) {
                        $item['status'] = 2;
                        Db::name("log")->where("id", $item['id'])->update(['status' => 2]);
                        $item['status_name'] = '生成失败';
                    } else {
                        $task_info = $this->getTaskTstatus($item['uid']);
                        if ($task_info['task_info']['status'] == 'running') {
                            $item['progress'] = $task_info['task_info']['progress'];
                            $currentStatus = $task_info['task_info']['current_step'];

// 从缓存中获取已存在的状态列表（用逗号分隔存储）
                            $cachedStatuses = Cache::get($item['uid'] . '_status_list') ? explode(',', Cache::get($item['uid'] . '_status_list')) : [];

// 定义可能的随机状态
                            $statusOptions = ['联网检索中', 'RAG 查询中', '内容生成中', '网页内容解析中'];

// 保持一个状态池，用于随机选择
                            $statusPool = array_diff($statusOptions, $cachedStatuses);

                            if (in_array($currentStatus, $cachedStatuses)) {
                                // 如果状态池为空，重置状态池
                                if (empty($statusPool)) {
                                    $statusPool = $statusOptions;
                                    $cachedStatuses = []; // 清空缓存中的已选状态
                                }
                                // 从状态池中随机选择
                                $randomStatus = $statusPool[array_rand($statusPool)];
                                $item['statusText'] = $randomStatus;
                                $cachedStatuses[] = $randomStatus; // 添加随机状态到缓存
                                $item['test'] = 2; // 标记为随机状态
                            } else {
                                // 如果当前状态不存在于缓存中，直接使用当前状态
                                $item['statusText'] = $currentStatus;
                                $cachedStatuses[] = $currentStatus; // 添加当前状态到缓存
                                $item['test'] = 1; // 标记为新状态
                            }

// 更新缓存，重新存储状态列表
                            Cache::set($item['uid'] . '_status_list', implode(',', $cachedStatuses), 3600);

// 保存调试信息
                            $item['cachedStatuses'] = $cachedStatuses;
                            $item['statusPool'] = $statusPool; // 记录剩余可选状态池
                        }else{
                            $item['statusText'] = '等待中';
                            $item['progress'] = 0;
                        }
                    }
                } elseif ($item['status'] == 2) {
                    $item['status_name'] = '生成失败';
                } elseif ($item['status'] == 3) {
                    $item['progress'] = 0;
                } else {
                    $item['progress'] = 100;
                    $item['status_name'] = '已完成';
                }

                return $item;
            })->toArray();
        return retJson($result);
    }


    public function check($uid = '')
    {
        $url = "http://192.168.10.190:8211/check/";

// 初始化cURL会话
        $ch = curl_init($url);

// 设置cURL选项
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // 返回结果不直接输出
        curl_setopt($ch, CURLOPT_POST, true); // 设置为POST请求
        curl_setopt($ch, CURLOPT_POSTFIELDS, "uid=" . $uid); // POST请求的数据

// 执行cURL会话
        $response = curl_exec($ch);

// 检查是否有错误发生
        if (curl_errno($ch)) {
            return retError('操作失败');
        }

// 关闭cURL资源
        curl_close($ch);

// 输出响应
        $result = json_decode($response, true);
        $status = 0;
        if ($result['code'] == 200 && $result['status'] == 1) {
            $status = $result['status'];
            Db::name("log")->where("uid", $uid)->update(['status' => 1, 'file_path' => $result['url']]);
        }
        return $status;
    }


}
